<template>
	<div class="live-public-screen">
		<el-card class="screen-card">
			<template #header>
				<div class="screen-header">
					<div class="header-title">
						<el-badge :value="onlineCount" class="online-count-badge">
							<h2>直播公屏</h2>
						</el-badge>
					</div>
					<div class="header-controls">
						<el-input v-model="searchKeyword" placeholder="搜索消息" :prefix-icon="Search" clearable
							@input="handleSearch" style="width: 200px;"></el-input>

						<el-select v-model="filterType" placeholder="消息类型" @change="handleFilter">
							<el-option label="全部消息" value="all"></el-option>
							<el-option label="普通消息" value="normal"></el-option>
							<el-option label="礼物消息" value="gift"></el-option>
							<el-option label="进场消息" value="enter"></el-option>
						</el-select>

						<el-button-group>
							<el-tooltip content="暂停滚动">
								<el-button :type="autoScroll ? 'default' : 'primary'"
									:icon="autoScroll ? VideoPlay : VideoPause" @click="toggleAutoScroll"></el-button>
							</el-tooltip>
							<el-tooltip content="清空屏幕">
								<el-button type="danger" :icon="Delete" @click="clearScreen"></el-button>
							</el-tooltip>
							<el-tooltip content="导出消息">
								<el-button type="success" :icon="Download" @click="exportMessages"></el-button>
							</el-tooltip>
						</el-button-group>
					</div>
				</div>
			</template>

			<div class="screen-content" ref="screenContent">
				<el-empty v-if="displayMessages.length === 0" description="暂无消息"></el-empty>

				<el-timeline v-else>
					<el-timeline-item v-for="message in displayMessages" :key="message.id"
						:timestamp="formatTime(message.timestamp)" :type="getTimelineItemType(message.type)"
						:hollow="message.highlighted">
						<el-card :class="['message-card', message.type, { highlighted: message.highlighted }]">
							<div class="message-user">
								<el-avatar :size="32"
									:src="message.avatar">{{ message.username.substr(0, 1) }}</el-avatar>
								<div class="user-info">
									<div class="username">
										{{ message.username }}
										<el-tag v-if="message.userType === 'admin'" size="small"
											type="danger">管理员</el-tag>
										<el-tag v-else-if="message.userType === 'vip'" size="small"
											type="warning">VIP</el-tag>
									</div>
									<div class="user-level">Lv.{{ message.userLevel || 1 }}</div>
								</div>
							</div>

							<div class="message-content">
								<p v-if="message.type === 'normal'">{{ message.content }}</p>
								<p v-else-if="message.type === 'gift'" class="gift-message">
									<el-icon>
										<Present />
									</el-icon>
									{{ message.content }}
								</p>
								<p v-else-if="message.type === 'enter'" class="enter-message">
									<el-icon>
										<UserFilled />
									</el-icon>
									{{ message.content }}
								</p>
							</div>

							<div class="message-actions">
								<el-dropdown trigger="click" @command="handleMessageAction($event, message.id)">
									<el-button type="text" size="small">
										<el-icon>
											<More />
										</el-icon>
									</el-button>
									<template #dropdown>
										<el-dropdown-menu>
											<el-dropdown-item command="delete">删除消息</el-dropdown-item>
											<el-dropdown-item command="highlight">标记消息</el-dropdown-item>
											<el-dropdown-item command="ban" divided>禁言用户</el-dropdown-item>
											<el-dropdown-item command="report">举报用户</el-dropdown-item>
										</el-dropdown-menu>
									</template>
								</el-dropdown>
							</div>
						</el-card>
					</el-timeline-item>
				</el-timeline>
			</div>

			<div class="screen-footer">
				<el-pagination background layout="total, prev, pager, next, jumper" :total="totalMessages"
					:page-size="pageSize" :current-page="currentPage" @current-change="handlePageChange"
					hide-on-single-page></el-pagination>
			</div>
		</el-card>
	</div>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		onUnmounted,
		watch,
		nextTick
	} from 'vue';
	import {
		Search,
		Delete,
		Download,
		VideoPlay,
		VideoPause,
		Present,
		UserFilled,
		More
	} from '@element-plus/icons-vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';

	// 模拟数据，实际应用中应该从API或WebSocket获取
	const generateMockMessages = (count) => {
		const messages = [];
		const types = ['normal', 'gift', 'enter'];
		const userTypes = ['normal', 'normal', 'normal', 'vip', 'admin'];

		for (let i = 0; i < count; i++) {
			const type = types[Math.floor(Math.random() * types.length)];
			const userType = userTypes[Math.floor(Math.random() * userTypes.length)];
			const username = `用户${Math.floor(Math.random() * 1000)}`;

			let content = '';
			if (type === 'normal') {
				content = `这是一条普通消息 ${Math.floor(Math.random() * 1000)}`;
			} else if (type === 'gift') {
				content = `送出了${Math.floor(Math.random() * 10) + 1}个礼物`;
			} else {
				content = '进入了直播间';
			}

			messages.push({
				id: i + 1,
				username,
				avatar: `https://randomuser.me/api/portraits/${Math.random() > 0.5 ? 'men' : 'women'}/${i % 100}.jpg`,
				content,
				type,
				timestamp: Date.now() - Math.floor(Math.random() * 1000 * 60 * 60),
				userType,
				userLevel: Math.floor(Math.random() * 30) + 1,
				highlighted: false
			});
		}

		return messages.sort((a, b) => b.timestamp - a.timestamp);
	};

	// 状态管理
	const messages = ref(generateMockMessages(20));
	const searchKeyword = ref('');
	const filterType = ref('all');
	const currentPage = ref(1);
	const pageSize = ref(10);
	const screenContent = ref(null);
	const autoScroll = ref(true);
	const onlineCount = ref(Math.floor(Math.random() * 5000) + 1000);

	// 计算属性：过滤和分页后的消息
	const filteredMessages = computed(() => {
		let result = [...messages.value];

		// 按类型过滤
		if (filterType.value !== 'all') {
			result = result.filter(msg => msg.type === filterType.value);
		}

		// 按关键词搜索
		if (searchKeyword.value) {
			const keyword = searchKeyword.value.toLowerCase();
			result = result.filter(msg =>
				msg.content.toLowerCase().includes(keyword) ||
				msg.username.toLowerCase().includes(keyword)
			);
		}

		// 按时间排序（新消息在前）
		return result.sort((a, b) => b.timestamp - a.timestamp);
	});

	const totalMessages = computed(() => filteredMessages.value.length);

	const displayMessages = computed(() => {
		const start = (currentPage.value - 1) * pageSize.value;
		const end = start + pageSize.value;
		return filteredMessages.value.slice(start, end);
	});

	// 方法
	const formatTime = (timestamp) => {
		const date = new Date(timestamp);
		return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
	};

	const getTimelineItemType = (messageType) => {
		switch (messageType) {
			case 'gift':
				return 'success';
			case 'enter':
				return 'info';
			default:
				return '';
		}
	};

	const handleSearch = () => {
		currentPage.value = 1; // 重置到第一页
	};

	const handleFilter = () => {
		currentPage.value = 1; // 重置到第一页
	};

	const handlePageChange = (page) => {
		currentPage.value = page;
	};

	const toggleAutoScroll = () => {
		autoScroll.value = !autoScroll.value;
		if (autoScroll.value) {
			scrollToBottom();
		}
	};

	const scrollToBottom = async () => {
		if (autoScroll.value && screenContent.value) {
			await nextTick();
			screenContent.value.scrollTop = screenContent.value.scrollHeight;
		}
	};

	const handleMessageAction = (action, messageId) => {
		const index = messages.value.findIndex(msg => msg.id === messageId);
		if (index === -1) return;

		const message = messages.value[index];

		switch (action) {
			case 'delete':
				ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					messages.value.splice(index, 1);
					ElMessage.success('消息已删除');
				}).catch(() => {});
				break;

			case 'highlight':
				messages.value[index].highlighted = !message.highlighted;
				ElMessage.success(message.highlighted ? '消息已标记' : '取消标记');
				break;

			case 'ban':
				ElMessageBox.confirm(`确定要禁言用户 ${message.username} 吗？`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					// 在实际应用中，这里应该调用API禁言用户
					ElMessage.success(`用户 ${message.username} 已被禁言`);
				}).catch(() => {});
				break;

			case 'report':
				// 在实际应用中，这里应该显示举报对话框
				ElMessage.info(`已举报用户 ${message.username}`);
				break;
		}
	};

	const clearScreen = () => {
		ElMessageBox.confirm('确定要清空所有消息吗？', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			messages.value = [];
			ElMessage.success('已清空屏幕');
		}).catch(() => {});
	};

	const exportMessages = () => {
		// 导出消息为CSV
		const header = "时间,用户名,类型,内容\n";
		const csvContent = filteredMessages.value.reduce((acc, msg) => {
			const time = new Date(msg.timestamp).toLocaleString();
			const row = `"${time}","${msg.username}","${msg.type}","${msg.content}"\n`;
			return acc + row;
		}, header);

		const blob = new Blob([csvContent], {
			type: 'text/csv;charset=utf-8;'
		});
		const url = URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.setAttribute('href', url);
		link.setAttribute('download', `直播消息记录_${new Date().toISOString().split('T')[0]}.csv`);
		link.style.visibility = 'hidden';
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);

		ElMessage.success('消息记录已导出');
	};

	// 模拟WebSocket连接接收新消息
	let messageTimer;
	const addRandomMessage = () => {
		const types = ['normal', 'normal', 'normal', 'gift', 'enter'];
		const userTypes = ['normal', 'normal', 'normal', 'vip', 'admin'];
		const randomType = types[Math.floor(Math.random() * types.length)];
		const randomUserType = userTypes[Math.floor(Math.random() * userTypes.length)];
		const username = `用户${Math.floor(Math.random() * 1000)}`;

		let content = '';
		if (randomType === 'normal') {
			content = `这是一条普通消息 ${Math.floor(Math.random() * 1000)}`;
		} else if (randomType === 'gift') {
			content = `送出了${Math.floor(Math.random() * 10) + 1}个礼物`;
		} else {
			content = '进入了直播间';
		}

		const newMessage = {
			id: Date.now(),
			username,
			avatar: `https://randomuser.me/api/portraits/${Math.random() > 0.5 ? 'men' : 'women'}/${Math.floor(Math.random() * 100)}.jpg`,
			content,
			type: randomType,
			timestamp: Date.now(),
			userType: randomUserType,
			userLevel: Math.floor(Math.random() * 30) + 1,
			highlighted: false
		};

		messages.value.unshift(newMessage);

		// 如果当前正在查看第一页，且启用了自动滚动，则保持在第一页
		if (currentPage.value === 1 && autoScroll.value) {
			scrollToBottom();
		}

		// 随机更新在线人数
		if (Math.random() > 0.7) {
			const delta = Math.floor(Math.random() * 20) - 10; // -10 到 10 的随机数
			onlineCount.value = Math.max(1, onlineCount.value + delta);
		}

		// 如果消息过多，可以限制数量
		if (messages.value.length > 200) {
			messages.value = messages.value.slice(0, 200);
		}
	};

	// 监听消息变化，自动滚动到底部
	watch(() => displayMessages.value, () => {
		if (currentPage.value === 1 && autoScroll.value) {
			scrollToBottom();
		}
	}, {
		deep: true
	});

	onMounted(() => {
		// 模拟每3秒收到一条新消息
		messageTimer = setInterval(addRandomMessage, 3000);

		// 初始滚动到底部
		scrollToBottom();
	});

	onUnmounted(() => {
		clearInterval(messageTimer);
	});
</script>

<style scoped>
	.live-public-screen {
		width: 100%;
		max-width: 900px;
		margin: 0 auto;
	}

	.screen-card {
		margin-bottom: 20px;
	}

	.screen-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.header-title {
		display: flex;
		align-items: center;
	}

	.online-count-badge {
		margin-right: 10px;
	}

	.header-controls {
		display: flex;
		gap: 10px;
		align-items: center;
	}

	.screen-content {
		height: 500px;
		overflow-y: auto;
		padding: 10px;
		margin: 10px 0;
		border: 1px solid #e4e7ed;
		border-radius: 4px;
		background-color: #f5f7fa;
	}

	.message-card {
		margin-bottom: 5px;
		border-radius: 4px;
		position: relative;
	}

	.message-card.gift {
		background-color: #f0f9eb;
	}

	.message-card.enter {
		background-color: #f2f6fc;
	}

	.message-card.highlighted {
		background-color: #fdf6ec;
		border: 1px solid #faecd8;
	}

	.message-user {
		display: flex;
		align-items: center;
		margin-bottom: 8px;
	}

	.user-info {
		margin-left: 10px;
	}

	.username {
		font-weight: bold;
		color: #409eff;
		display: flex;
		align-items: center;
		gap: 5px;
	}

	.user-level {
		font-size: 12px;
		color: #909399;
	}

	.message-content {
		margin: 10px 0;
		word-break: break-all;
	}

	.gift-message {
		color: #67c23a;
		display: flex;
		align-items: center;
		gap: 5px;
	}

	.enter-message {
		color: #909399;
		display: flex;
		align-items: center;
		gap: 5px;
	}

	.message-actions {
		position: absolute;
		top: 10px;
		right: 10px;
		opacity: 0;
		transition: opacity 0.3s;
	}

	.message-card:hover .message-actions {
		opacity: 1;
	}

	.screen-footer {
		padding: 10px 0;
		display: flex;
		justify-content: center;
	}
</style>
